package com.example.game;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileOutputStream;
import java.io.IOException;

public class RegisterActivity extends AppCompatActivity {

    private EditText et_reg_uname, et_reg_upass;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register); // 确保你有一个注册界面的布局文件

        initView();
    }

    private void initView() {
        et_reg_uname = findViewById(R.id.et_reg_uname);
        et_reg_upass = findViewById(R.id.et_reg_upass);
        btn_register = findViewById(R.id.btn_register);

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerUser();
            }
        });
    }

    private void registerUser() {
        String uname = et_reg_uname.getText().toString().trim();
        String upass = et_reg_upass.getText().toString().trim();

        if (TextUtils.isEmpty(uname) || TextUtils.isEmpty(upass)) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存用户信息到 SharedPreferences
        boolean isRegistered = SPDataUtil.saveUserInfo(this, uname, upass);
        if (isRegistered) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            // 注册成功后跳转到 MainActivity
            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
            startActivity(intent);
            finish(); // 结束 RegisterActivity
        } else {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean writeUserInfoToFile(String uname, String upass) {
        try (FileOutputStream fos = openFileOutput("userinfo.txt", MODE_PRIVATE)) {
            String data = uname + "," + upass;
            fos.write(data.getBytes());
            Log.i("RegisterActivity", "用户信息写入成功: " + data); // 添加日志输出
            return true;
        } catch (IOException e) {
            Log.e("RegisterActivity", "写入用户信息失败", e); // 添加日志输出
            e.printStackTrace();
            return false;
        }
    }
}